import { Button, message, Table, Divider, Popconfirm } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { FormattedMessage } from "umi";
import React, { useState, useRef, useEffect, Input } from "react";
import ProTable from "@ant-design/pro-table";
import { PageContainer } from "@ant-design/pro-layout";
import moment from "moment";
import { removeMenu, getList } from "./api";
import UpdateForm from "./components/UpdateForm";
import styles from "./index.less";

// 主数据格式化
const setList = (arr) => {
  const newTreeData = [];
  arr.map((item) => {
    const obj = { ...item };

    if (item.children && item.children.length) {
      obj.children = setList(item.children);
    } else {
      obj.children = null;
    }
    newTreeData.push(obj);
    return "";
  });
  return newTreeData;
};

// 部门格式化
const setTreeFormat = (data) => {
  const newData = [];
  data.map((item) => {
    const obj = {
      id: item.deptId,
      value: item.deptId,
      title: item.deptName,
      pId: item.parentId,
      isLeaf: false,
    };
    newData.push(obj);
    return "";
  });
  return newData;
};

/**
 * @zh-CN 主类
 *
 * @param
 */
const TableList = () => {
  const actionRef = useRef();

  const [pagination, setPagination] = useState({ current: 1, pageSize: 20 });
  const [currentIndex, setCurrentIndex] = useState(0); // 默认排序

  const ProTableOoChange = ({ current, pageSize }) => {
    setPagination({ current, pageSize });
  };

  const getListData = async (fields) => {
    try {
      const res = await getList({ ...fields });
      if (res && res.code === 0) {
        setCurrentIndex(res.data.total);
        return { data: res.data.list };
      }
      message.error(res.msg || "请求失败，请重试");
      return;
    } catch (error) {
      message.error("请求失败，请重试");
      return false;
    }
  };

  // 更新数据 组件 ------------------------------------------------------------------

  const [type, setType] = useState();

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updataData, setUpdataData] = useState({});

  const closeUpdateForm = () => {
    handleUpdateModalVisible(false);
  };

  const setUpdateForm = (param, index) => {
    setType("updata");
    handleUpdateModalVisible(true);
    setUpdataData(param);
  };

  const updataSuccess = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 添加
  const addData = () => {
    setType("add");
    setUpdataData({});
    handleUpdateModalVisible(true);
  };

  // ----------------------------------------------结束------------------------------------------------------

  const handleRemove = (id) => {
    const hide = message.loading("正在删除");
    removeMenu(id).then((res) => {
      hide();
      if (res.code === 0) {
        message.success("删除成功！");
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(res.msg || "删除失败，请重试");
      }
    });
  };

  useEffect(() => {}, []);

  const columns = [
    {
      title: "序号",
      valueType: "option",
      dataIndex: "",
      render(text, record, index) {
        return (
          <span key={index}>
            {(pagination.current - 1) * pagination.pageSize + index + 1}
          </span>
        );
      },
    },
    {
      title: "名称",
      dataIndex: "name",
    },
    {
      title: "单位简称",
      dataIndex: "abbreviation",
    },
    {
      title: "状态",
      dataIndex: "status",
      hideInSearch: true,
      render: (_, record) => {
        return <>{record.status === 0 ? "禁用" : "激活"}</>;
      },
    },
    {
      title: "链接状态",
      dataIndex: "onlineState",
      hideInSearch: true,
      valueEnum: {
        0: {
          text: "下线",
          status: "Default",
        },
        1: {
          text: "在线",
          status: "Success",
        },
      },
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createTime',
    //   valueType: 'option',
    //   render: (_, record) => {
    //     return <>{moment(record.createTime).format('YYYY-MM-DD')}</>
    //   }
    // },
    {
      title: "操作",
      dataIndex: "opt",
      valueType: "option",
      render: (_, record, index) => {
        const text = (
          <>
            <Button type="link" onClick={() => setUpdateForm(record, index)}>
              编辑
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="确实要删除此条信息吗？"
              onConfirm={() => handleRemove(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link">删除</Button>
            </Popconfirm>
          </>
        );
        return <>{text}</>;
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={(record) => record.id}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={addData}>
            <PlusOutlined />{" "}
            <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={getListData}
        columns={columns}
        onChange={ProTableOoChange}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows)
        //   }
        // }}
      />

      <UpdateForm
        visible={updateModalVisible}
        onCancel={closeUpdateForm}
        data={updataData}
        currentIndex={currentIndex}
        onSuccess={updataSuccess}
        type={type}
      />
    </PageContainer>
  );
};

export default TableList;
